class UsersController < ApplicationController
  def index
    @user = User.find(:all)
		respond_to do |format|
			format.html	#index.html
		end
	end

  def show
    @user = User.find(params[:id])
    respond_to do |format|
      format.html
      format.xml {render :xml => @user.to_xml}
    end
  end

  def new
    @users = User.new
  end

  def create
    @user = User.new(params[:user])
    

    respond_to do |format|
      if @user.save
        format.html {redirect_to user_url(@user)}
        format.xml {head :created, location => user_url(@user)}
      else
        format.html {render :action => "new"}
        format.xml {render :xml => @user.errors.to_xml}
        format.xml {render :xml => @user.errors.to_xml}
      end
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])

	p params
    respond_to do |format|
		if( @user.update_attribute(:login, params[:user][:login]) &&
			@user.update_attribute(:email, params[:user][:email]) &&
			@user.update_attribute(:profil, params[:user][:profil]))
			  flash[:notice] = "Enregistrement réussi"
			  format.html {redirect_to user_url(@user)}
		end
    end
  end
  
# def update
  # params[:user].delete(:password) if params[:user][:password].blank?
  # if @user.update_attributes(params[:user])
    # flash[:success] = "Edit Successful."
    # redirect_to @user
  # else
    # @title = "Edit user"
    # render 'edit'
  # end
# end

  def destroy
    @user = User.find(params[:id])
    @user.destroy

    respond_to do |format|
      format.html {redirect_to users_path}
    end
  end

  def login
    return unless request.post?
    user = User.authenticate(params[:login], params[:password])

    if user
      session[:user_id] = user.id
      flash[:notice] = "Bienvenue #{user.login}!"
#      redirect_to 'index'
      target = session[:original_uri] || ''
      session[:original_uri] = nil
      redirect_to target
    else
      session[:user_id] = nil
      flash[:error] = 'Login ou mot de passe incorrect'
	  params[:login] = ''
	  params[:password] = nil
    end
  end
  
  def logout
    session[:user_id] = nil
    flash[:notice] = 'A bientot!'
    redirect_to ''
  end
end
